package com.ssy.lingxi.system.service.impl;

import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.PageModel;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberAuthTypeConfigFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.AuthConfigVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.DeleteAuthConfigVO;
import com.ssy.lingxi.sms.api.model.SmsConfigVO;
import com.ssy.lingxi.sms.api.model.request.DeleteConfigRequest;
import com.ssy.lingxi.system.dao.AuthParametersRepository;
import com.ssy.lingxi.system.dto.request.AuthParametersDeleteRequest;
import com.ssy.lingxi.system.dto.request.AuthParametersSavOrUpdateRequest;
import com.ssy.lingxi.system.dto.response.MiddlegroundUserLoginResponse;
import com.ssy.lingxi.system.entity.AuthParameters;
import com.ssy.lingxi.system.entity.CommonParameters;
import com.ssy.lingxi.system.service.AuthParametersService;
import com.ssy.lingxi.system.utils.UserDetailsUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 实名验证配置
 *
 * @author Administrator
 */
@Service
public class AuthParametersServiceImpl implements AuthParametersService {
    @Resource
    private AuthParametersRepository authParametersRepository;
    @Resource
    private UserDetailsUtil userDetailsUtil;
    @Resource
    private MemberAuthTypeConfigFeign memberAuthTypeConfigFeign;

    /**
     * 查询实名验证公共参数列表
     *
     * @param authType 实名验证类型: 1-百度
     * @return 实名验证公共参数列表
     */
    @Override
    public Wrapper<PageData<AuthParameters>> authCommonList(PageModel request, Integer authType) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("id").ascending());
        Page<AuthParameters> all = authParametersRepository.findByAuthType(authType, page);
        return Wrapper.success(new PageData<>(all.getTotalElements(), all.getContent()));
    }

    /**
     * 添加或修改实名验证公共参数
     *
     * @param request            参数请求体
     * @param httpServletRequest httpServletRequest
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper authCommonSavOrUpdate(HttpServletRequest httpServletRequest, AuthParametersSavOrUpdateRequest request) {
        //判断是新增还是修改
        if (request.getId() != null && request.getId() > 0) {
            //修改
            AuthParameters authParameters = authParametersRepository.findById(request.getId()).orElse(null);
            if (authParameters == null) {
                return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
            }
            List<AuthParameters> allByCodeEquals = authParametersRepository.findAllByCodeEquals(request.getCode());
            if (allByCodeEquals.size() > 0) {
                Map<Long, AuthParameters> collect = allByCodeEquals.stream().collect(Collectors.toMap(AuthParameters::getId, v -> v));
                collect.remove(request.getId());
                if (collect.size() > 0) {
                    return Wrapper.fail("参数代码已存在请不要重复添加");
                }
            }
            BeanUtils.copyProperties(request, authParameters);
            authParameters.setUpdateTime(System.currentTimeMillis());
            authParametersRepository.save(authParameters);
            //调用会员服务->同步保存实名验证信息
            AuthConfigVO authConfigVO = new AuthConfigVO();
            authConfigVO.setCode(request.getCode());
            authConfigVO.setRemark(request.getDescribe());
            authConfigVO.setAuthType(request.getAuthType());
            authConfigVO.setValue(request.getValue());
            memberAuthTypeConfigFeign.saveOrUpdateAuthConfig(authConfigVO);
            return Wrapper.success();
        } else {
            //新增
            List<AuthParameters> allByCodeEquals = authParametersRepository.findAllByCodeEquals(request.getCode());
            if (allByCodeEquals.size() > 0) {
                return Wrapper.fail(ResponseCode.THE_CODE_HAS_EXIST);
            }
            MiddlegroundUserLoginResponse loginUserDetails = userDetailsUtil.getLoginUserDetails(httpServletRequest);
            AuthParameters authParameters = new AuthParameters();
            BeanUtils.copyProperties(request, authParameters);
            authParameters.setCreateTime(System.currentTimeMillis());
            authParameters.setCreateRoleId(loginUserDetails.getId());
            authParametersRepository.save(authParameters);
            //调用会员服务->同步保存实名验证信息
            AuthConfigVO authConfigVO = new AuthConfigVO();
            authConfigVO.setCode(request.getCode());
            authConfigVO.setRemark(request.getDescribe());
            authConfigVO.setAuthType(request.getAuthType());
            authConfigVO.setValue(request.getValue());
            memberAuthTypeConfigFeign.saveOrUpdateAuthConfig(authConfigVO);
            return Wrapper.success();
        }

    }

    /**
     * 删除实名验证公共参数
     *
     * @param request 请求参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper authCommonDelete(AuthParametersDeleteRequest request) {
        AuthParameters authParameters = authParametersRepository.findById(request.getId()).orElse(null);
        if (authParameters != null) {
            authParametersRepository.deleteById(request.getId());
            DeleteAuthConfigVO deleteAuthConfigVO = new DeleteAuthConfigVO();
            deleteAuthConfigVO.setCode(authParameters.getCode());
            deleteAuthConfigVO.setAuthType(authParameters.getAuthType());
            memberAuthTypeConfigFeign.deleteAuthConfig(deleteAuthConfigVO);
        }
        return Wrapper.success();
    }

    /**
     * 清空实名验证内容
     *
     * @return 是否成功
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Boolean clearAuth() {
        authParametersRepository.deleteAllInBatch();
        memberAuthTypeConfigFeign.clearAuth();
        return true;
    }
}
